/**
 *Copyright(c) HNA SYSTEMS Co., LTD
 *
 *@date 2013-7-18
 * 	
 *Original Author: 郑兴(zhengxing)
 *
 *ChangeLog
 *
 */
package com.hnas.core.spring;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.beans.factory.config.PropertyOverrideConfigurer;

/**
 * 
 * @author 郑兴(zhengxing)
 *
 */
public class EncryptedPropertyOverrideConfigurer extends
		PropertyOverrideConfigurer {
	/*
	 * (non-Javadoc)
	 * @see org.springframework.beans.factory.config.PropertyResourceConfigurer#convertPropertyValue(java.lang.String)
	 */
	protected String convertPropertyValue(String originalValue) {
		return decrypt(originalValue);
	}
	
	/**
	 * <pre>解密</pre>
	 * @Auther 郑兴(zhengxing)
	 * @param originalValue
	 * @return
	 */
	private String decrypt(String originalValue) {
		try {
			return decode(originalValue);
		} catch (Exception e) {
			throw new RuntimeException("decode original value error.",e);
		}
	}
	
	public static String decode(String secret) throws NoSuchPaddingException,
			NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
			IllegalBlockSizeException,UnsupportedEncodingException {
		byte[] kbytes = "jaas is the way".getBytes("UTF-8");
		SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");

		BigInteger n = new BigInteger(secret, 16);
		byte[] encoding = n.toByteArray();

		Cipher cipher = Cipher.getInstance("Blowfish");
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decode = cipher.doFinal(encoding);
		return new String(decode,"UTF-8");
	}

	public static String encode(String secret) throws NoSuchPaddingException,
			NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
			IllegalBlockSizeException,UnsupportedEncodingException {
		byte[] kbytes = "jaas is the way".getBytes("UTF-8");
		SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");

		Cipher cipher = Cipher.getInstance("Blowfish");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] encoding = cipher.doFinal(secret.getBytes("UTF-8"));
		BigInteger n = new BigInteger(encoding);
		return n.toString(16);
	}
	
	public static void main(String[] args) throws Exception {
//		String org = "jdbc:oracle:thin:@(description=(address=(host=10.21.137.120)(protocol=tcp)(port=1521))(connect_data=(sid=zx)))";
		String org = "64c5fd2979a86168";
		//String encode = encode(org);
		//System.out.println(encode);
		System.out.println(decode(org));
	}
}